import os, sys, glob

def print_threadlet(nrecord, nth, indent):
	print(indent + 'tl%d(%d)' % (nth, nrecord))

def display_thread_log(f, indent):
	basename = os.path.basename(f.name)
	print(''.join([indent, basename, ':']))
	nested = 0
	ntl = 0
	nrecord = 0
	indent = indent + '\t'
	for line in f:
		if 'CS' in line:
			print_threadlet(nrecord, ntl, indent)
			ntl += 1
			nrecord = 0
			print(indent + line[:-1])
		elif 'PS' in line:
			nested_dir = line.split()[-1]
			if 'Enter' in line:
				print_threadlet(nrecord, ntl, indent)
				ntl += 1
				nrecord = 0
				print(''.join([indent, 'Enter nested PS', str(nested)]))
				display_parallel_section(nested_dir, indent)
			else:
				print(''.join([indent, 'Leave nested PS', str(nested)]))
				nested += 1
		else:
			nrecord += 1
	print_threadlet(nrecord, ntl, indent)

def display_parallel_section(path, indent):
	if not os.path.exists(path):
		print(indent + 'Error: unknown path')
		return
	files = sorted(glob.glob(path + '/THREAD*'), key=lambda s:int(s[s.rfind('D') + 1:]))
	for fname in files:
		with open(fname) as thread_log_file:
			display_thread_log(thread_log_file, indent)

if __name__ == '__main__':
	if len(sys.argv) == 1:
		start_dir = '.'
	else:
		start_dir = sys.argv[1]
	if start_dir[-1] != '/':
		start_dir = start_dir + '/'
	get_int = lambda s:int(s[s.rfind('S') + 1:s.rfind('_in')])
	top_ps_dirs = sorted(glob.glob(start_dir + 'PS*_in_THREAD*'), key=get_int)
	for psdir in top_ps_dirs:
		print('Top level PS%d' % get_int(psdir))
		display_parallel_section(psdir, '')
		print('-----------------------------------')
